extends "res://scenes/enemies/enemy.gd"

@onready var player_sencer: Area2D = $PlayerSencer
var target_position = null
	
@onready var trail_scene = preload("res://scenes/effects/trail.tscn")

func _physics_process(_delta):
	var was_on_wall = is_on_wall()
	move_and_slide()
	if !was_on_wall && is_on_wall():
		direction *= -1

func _process(delta):
	if is_death:
		velocity.x = 0
		velocity.y += gravity * delta
		return 
 
	_cal_target_position()
	if target_position == null:
		velocity = velocity.move_toward(Vector2.ZERO, acceleration * delta)
	else:
		var direction = global_position.direction_to(target_position)
		velocity = velocity.move_toward(direction*max_speed, acceleration * delta)

	_set_face_direction(velocity)
	
func _set_face_direction(velocity):
	if velocity.x > 0:
		direction  = 1
	elif velocity.x < 0:
		direction = -1
	else:
		pass		
	super.set_face_direction(direction)

func _cal_target_position():
	var bodies = player_sencer.get_overlapping_bodies()
	if not bodies.is_empty():
		target_position = bodies[0].global_position+Vector2(0,-50)
		return target_position
		
	if target_position != null && global_position.distance_squared_to(target_position) < 25:
		target_position = null

# 死亡动画效果
func was_killed():
	_tween_scale()

func _tween_scale():
	var tween = get_tree().create_tween()
	tween.set_parallel(false)
	tween.set_ease (Tween.EASE_IN_OUT)
	tween.set_trans(Tween.TRANS_SPRING )
	tween.tween_property($Sprite2D, "rotation", 1.5, 0.1)
	tween.tween_property($Sprite2D, "position", Vector2(0,30), 0.1)

# 残影效果
func _on_trail_timer_timeout():
	if -6 < velocity.x and velocity.x < 6:
		return

	var tail = trail_scene.instantiate()
	get_parent().add_child(tail)
	get_parent().move_child(tail,get_index())

	var properties = [
		"hframes",
		"vframes",
		"frame",
		"texture",
		"global_position",
		"flip_h",
		"region_enabled",
		"region_rect",
		"region_filter_clip_enabled",
		"scale",
	]

	for name in properties:
		#print(name, sprite.get(name))
		tail.set(name, sprite.get(name))
